import { login, sendCode } from '@/store/actions/login'
import { LoginForm } from '@/types/data'
import { Button, Form, Input, NavBar, Toast } from 'antd-mobile'
import { InputRef } from 'antd-mobile/es/components/input'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory, useLocation } from 'react-router-dom'
import styles from './index.module.scss'

const Login = () => {
  const history = useHistory()

  const dispatch = useDispatch()

  // 手机输入框的引用
  const mobileInputRef = useRef<InputRef>(null)

  // 表单的引用
  const [form] = Form.useForm()

  // 定时器引用
  const timerRef = useRef<number>()

  // 倒计时计数
  const [seconds, setSeconds] = useState(0)

  // 发送验证码
  const onSendCode = () => {
    // 正在倒计时，阻止后续的点击
    if (seconds > 0) return
    const mobile = form.getFieldValue('mobile')
    const errors = form.getFieldError('mobile')

    // 当手机号验证不通过时，聚焦输入框
    if (errors.length > 0) {
      return mobileInputRef.current?.focus
    }
    dispatch(sendCode(mobile))

    // 重置倒计时秒数
    setSeconds(59)
    timerRef.current = window.setInterval(() => {
      setSeconds((s) => s - 1)
    }, 1000)
  }

  // 倒计时结束时清理定时器
  useEffect(() => {
    if (seconds <= 0) {
      clearInterval(timerRef.current)
    }
  }, [seconds])

  // 组件销毁时清理定时器
  useEffect(() => {
    return () => {
      clearInterval(timerRef.current)
    }
  }, [])

  // 登录
  const location = useLocation<{ from: string }>()
  const doLogin = async (values: LoginForm) => {
    await dispatch(login(values))

    // 弹出提示框
    Toast.show({
      content: '登录成功',
      duration: 1000,

      // 提示框消失后，跳转页面
      afterClose: () => {
        // history.push('/home')
        history.replace(location.state?.from || '/home')
      }
    })
  }

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>
        <Form
          form={form}
          onFinish={doLogin}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true
          }}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }
            ]}
          >
            <Input placeholder="请输入手机号" ref={mobileInputRef}></Input>
          </Form.Item>

          <Form.Item
            className="login-item"
            extra={
              <span
                className={seconds === 0 ? 'code-extra' : 'code-extra-disabled'}
                onClick={onSendCode}
              >
                {seconds === 0 ? '发送验证码' : `${seconds}`}
              </span>
            }
            name="code"
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码格式错误' }
            ]}
          >
            <Input placeholder="请输入验证码"></Input>
          </Form.Item>

          <Form.Item>
            <Button
              className="login-submit"
              type="submit"
              color="primary"
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
